"""
路线数据模型
"""
from django.db import models
from django.contrib.auth import get_user_model
from apps.attractions.models import Attraction

User = get_user_model()


class RouteDistance(models.Model):
    """路线距离表"""
    TRANSPORT_MODES = [
        ('driving', '自驾'),
        ('transit', '公交'),
        ('bicycling', '骑行'),
        ('walking', '步行'),
    ]
    
    from_attraction = models.ForeignKey(
        Attraction,
        on_delete=models.CASCADE,
        related_name='outgoing_routes',
        verbose_name='起始景点'
    )
    to_attraction = models.ForeignKey(
        Attraction,
        on_delete=models.CASCADE,
        related_name='incoming_routes',
        verbose_name='目标景点'
    )
    transport_mode = models.CharField(
        max_length=20,
        choices=TRANSPORT_MODES,
        default='driving',
        verbose_name='交通方式',
        db_index=True
    )
    distance = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='距离（公里）')
    travel_time = models.IntegerField(verbose_name='行程时间（分钟）', null=True, blank=True)
    transport_cost = models.DecimalField(max_digits=8, decimal_places=2, default=0, verbose_name='交通费用')
    cache_expire = models.DateTimeField(verbose_name='缓存过期时间', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'route_distances'
        verbose_name = '路线距离'
        verbose_name_plural = '路线距离'
        unique_together = ('from_attraction', 'to_attraction', 'transport_mode')

    def __str__(self):
        return f"{self.from_attraction.name} -> {self.to_attraction.name}"


class RoutePlan(models.Model):
    """用户路线规划记录"""
    TRANSPORT_MODES = [
        ('driving', '自驾'),
        ('transit', '公交'),
        ('bicycling', '骑行'),
        ('walking', '步行'),
    ]
    
    user_id = models.IntegerField(verbose_name='用户ID', null=True, blank=True)
    budget = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='预算')
    start_attraction = models.ForeignKey(
        Attraction,
        on_delete=models.CASCADE,
        related_name='route_plans',
        verbose_name='起始景点'
    )
    must_visit_attractions = models.JSONField(
        default=list,
        verbose_name='必须访问的景点ID列表',
        blank=True
    )
    transport_mode = models.CharField(
        max_length=20,
        choices=TRANSPORT_MODES,
        default='driving',
        verbose_name='交通方式'
    )
    optimal_route = models.JSONField(verbose_name='最优路线结果', default=dict)
    total_cost = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='总费用')
    total_distance = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='总距离')
    is_shared = models.BooleanField(default=False, verbose_name='是否分享')
    share_code = models.CharField(max_length=32, unique=True, null=True, blank=True, verbose_name='分享码')
    view_count = models.IntegerField(default=0, verbose_name='浏览量')
    share_count = models.IntegerField(default=0, verbose_name='分享次数')
    use_count = models.IntegerField(default=0, verbose_name='使用次数')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'route_plans'
        verbose_name = '路线规划'
        verbose_name_plural = '路线规划'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user_id', 'created_at']),  # 添加索引用于查询用户路线
            models.Index(fields=['is_shared', 'created_at']),  # 添加索引用于查询分享路线
            models.Index(fields=['share_code']),  # 添加索引用于查询分享码
        ]

    def __str__(self):
        return f"路线规划 #{self.id} - {self.start_attraction.name}"


class RouteFavorite(models.Model):
    """路线收藏"""
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='favorite_routes',
        verbose_name='用户'
    )
    route_plan = models.ForeignKey(
        RoutePlan,
        on_delete=models.CASCADE,
        related_name='favorited_by',
        verbose_name='路线'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='收藏时间')

    class Meta:
        db_table = 'route_favorites'
        verbose_name = '路线收藏'
        verbose_name_plural = '路线收藏'
        unique_together = ('user', 'route_plan')
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'created_at']),  # 添加索引用于查询用户收藏
            models.Index(fields=['route_plan', 'created_at']),  # 添加索引用于查询路线收藏数
        ]

    def __str__(self):
        return f"{self.user.username} 收藏了路线 #{self.route_plan.id}"
